import React, {createContext, ReactNode, useContext, useEffect, useState} from 'react';
import {Language, t as translateFunc} from './translations/index';

// 语言上下文类型
interface LanguageContextType {
  currentLanguage: Language;
  setLanguage: (language: Language) => void;
  t: (key: string) => string;
}

// 创建默认语言上下文值
const defaultLanguageContextValue: LanguageContextType = {
  currentLanguage: 'zh-CN',
  setLanguage: () => {
  },
  t: (key) => key,
};

// 创建语言上下文
export const LanguageContext = createContext<LanguageContextType>(defaultLanguageContextValue);

// 语言提供者组件的属性类型
interface I18nProviderProps {
  children: ReactNode;
  defaultLanguage?: Language;
}

// 语言提供者组件
export const I18nProvider: React.FC<I18nProviderProps> = ({
                                                            children,
                                                            defaultLanguage = 'zh-CN'
                                                          }) => {
  // 从本地存储中获取用户之前选择的语言，或使用默认语言
  const [currentLanguage, setCurrentLanguage] = useState<Language>(() => {
    const savedLanguage = localStorage.getItem('app-language');
    return (savedLanguage as Language) || defaultLanguage;
  });

  // 当语言改变时，保存到本地存储
  useEffect(() => {
    localStorage.setItem('app-language', currentLanguage);
  }, [currentLanguage]);

  // 设置语言函数
  const setLanguage = (language: Language) => {
    setCurrentLanguage(language);
  };

  // 翻译函数
  const t = (key: string): string => {
    return translateFunc(key, currentLanguage);
  };

  // 上下文值
  const contextValue: LanguageContextType = {
    currentLanguage,
    setLanguage,
    t,
  };

  return (
    <LanguageContext.Provider value={contextValue}>
      {children}
    </LanguageContext.Provider>
  );
};

// 使用语言Hook
export const useLanguage = (): LanguageContextType => {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within an I18nProvider');
  }
  return context;
};

// 再导出翻译函数
export {translateFunc as t};
export type {Language};

export default I18nProvider;
